<!---
  * 字段 下拉选择框
  * 
  * @Author:    1024创新实验室：罗伊
  * @Date:      2022-09-12 22:06:45 
  * @Wechat:    zhuda1024 
  * @Email:     lab1024@163.com 
  * @Copyright  1024创新实验室 （ https://1024lab.net ），Since 2012 
  *
-->
<template>
  <div>
    <uni-data-select :localdata="dictValueList" v-model="selectValue" :placeholder="props.placeholder" :clear="true" @change="onChange" />
  </div>
</template>

<script setup>
  import { onMounted, ref, watch } from 'vue';
  import { dictApi } from '@/api/support/dict-api';
  import { useDictStore } from '@/components/dict-select/dict';

  const props = defineProps({
    keyCode: String,
    modelValue: [String],
    placeholder: {
      type: String,
      default: '请选择',
    },
  });

  // -------------------------- 查询 字典数据 --------------------------

  const dictValueList = ref([]);

  // 缓存在pinia的字典数据
  const dictStore = useDictStore();

  /** smart-admin 原方法,
  async function queryDict() {
    let res = await dictApi.valueList(props.keyCode);
    dictValueList.value = res.data.map((e) => Object.assign({}, { text: e.valueName, value: e.valueCode }));
  }
  */


  /**
   * 获取字典数据
   * 返回数据格式：[{value: "1", text: "男"}, {value: "0", text: "女"}]
   * 2024-12-18 16:17:13
   */
  async function getDcit(){
    //1.先从pinia中获取字典数据
    let dict = dictStore.getDict(props.keyCode);
    dictValueList.value = dict;

    //2.如果pinia中没有字典数据，则从api接口获取
    if(dict === undefined || dict.length === 0){
      let res = await dictApi.getDictByCode(props.keyCode);
      dictValueList.value = res.result;

      //3.将字典数据存入pinia
      await dictStore.addDict(props.keyCode, res.result);
      console.log("已经将字典数据存入pinia", dictStore.getDict(props.keyCode));
    }
  }


  onMounted(getDcit);

  // -------------------------- 选中 相关、事件 --------------------------

  const selectValue = ref(props.modelValue);
  watch(
    () => props.modelValue,
    (value) => {
      selectValue.value = value;
    }
  );

  const emit = defineEmits(['update:modelValue', 'change']);
  function onChange(selectValue) {
    let find = dictValueList.value.filter((e) => e.value === selectValue)[0];
    emit('update:modelValue', find.value);
    emit('change', find.value, find.text);
  }
</script>
